/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package src;

import com.google.gdata.client.spreadsheet.SpreadsheetService;
import com.google.gdata.data.spreadsheet.CellEntry;
import com.google.gdata.data.spreadsheet.CellFeed;
import com.google.gdata.data.spreadsheet.SpreadsheetEntry;
import com.google.gdata.data.spreadsheet.SpreadsheetFeed;
import com.google.gdata.data.spreadsheet.WorksheetEntry;
import com.google.gdata.util.AuthenticationException;
import com.google.gdata.util.ServiceException;
import java.io.BufferedReader;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.util.List;

/**
 *
 * @author administrador
 */
public class ComputeUsage extends Thread
{

    SpreadsheetService myService;
    URL metafeedUrl;
    SpreadsheetFeed feed;
    WorksheetEntry defaulWorksheet;
    SpreadsheetEntry myWorksheet;
    URL cellFeedUrl;
    boolean autentic = false;
    WriteProprierts w = new WriteProprierts();

    void ComputeUsage()
    {
        try
        {
            autentic();

        }
        catch ( IOException ex )
        {
            Degub.getInstance().Debug( ex );
        }
        catch ( AuthenticationException ex )
        {
            Degub.getInstance().Debug( ex );
        }
        catch ( ServiceException ex )
        {
            Degub.getInstance().Debug( ex );
        }
    }

    private void autentic() throws IOException, AuthenticationException, ServiceException
    {
        if ( !autentic )
        {
            myService = new SpreadsheetService( "computeUsersQuicklyTranslator" );
            myService.setUserCredentials( "lcarlesso3@gmail.com", "carlesso" );

            metafeedUrl = new URL( "http://spreadsheets.google.com/feeds/spreadsheets/" );

            feed = myService.getFeed( metafeedUrl, SpreadsheetFeed.class );

            List<SpreadsheetEntry> spreadsheets = feed.getEntries();

            for ( int i = 0; i < spreadsheets.size(); i++ )
            {
                SpreadsheetEntry entry = spreadsheets.get( i );
                if ( entry.getTitle().getPlainText().equals( "computeUsersQuicklyTranslator" ) )
                {
                    myWorksheet = entry;
                }
            }

            defaulWorksheet = myWorksheet.getDefaultWorksheet();

            autentic = true;
        }
    }

    private int getNextRow() throws IOException, ServiceException
    {
        cellFeedUrl = myWorksheet.getWorksheets().get( 1 ).getCellFeedUrl();
        CellFeed fee = myService.getFeed( cellFeedUrl, CellFeed.class );


        return Integer.parseInt( ( fee.getEntries().get( 2 ).getCell().getInputValue() ).trim() );
    }

    private void computeNextRow() throws IOException, ServiceException
    {
        myService.insert( cellFeedUrl, new CellEntry( 2, 2, String.valueOf( getNextRow() + 1 ) ) );
    }

    private String getWanIp() throws IOException
    {
        URL url = new URL( "http://whatismyip.com/automation/n09230945NL.asp" );
        java.io.InputStream is = url.openStream();
        InputStreamReader isr = new InputStreamReader( is );
        BufferedReader br = new BufferedReader( isr );

        return br.readLine();
    }

    private String[] getIpAndHost()
    {
        String ipandHost[] = new String[ 2 ];
        try
        {
            InetAddress addr = InetAddress.getLocalHost();

            byte[] ipAddr = addr.getAddress();

            ipandHost[0] = ipAddr[0] + "." + ipAddr[1] + "." + ipAddr[2] + "." + ipAddr[3];

            ipandHost[1] = addr.getHostName();
        }
        catch ( UnknownHostException ex )
        {
        }
        {
        }

        return ipandHost;
    }

    public void setData()
    {
        setData( "", "", "" );
    }

    public void setData( String email, String updating, String name )
    {
        SetData s = new SetData( email, updating, name );
        s.start();
    }

    class SetData extends Thread
    {

        String email = null;
        String updating = null;
        String name = null;

        private SetData( String email, String updating, String name )
        {
            this.email = email;
            this.updating = updating;
            this.name = name;
        }

        @Override
        public void run()
        {
            try
            {
                autentic();
                Degub.getInstance().Debug( "Starting registering same data at server" );
                Calendar cal = Calendar.getInstance();
                WriteProprierts w = new WriteProprierts();
                StringBuffer values = new StringBuffer();
                values.append( " 1=" + email );
                values.append( ",2=" + name );
                values.append( ",3=" + w.read( WriteProprierts.RANKING ) );
                values.append( ",4=" + cal.getTime().toString() );
                values.append( ",5=" + getIpAndHost()[0] );
                values.append( ",6=" + getIpAndHost()[1] );
                values.append( ",7=" + getWanIp() );
                values.append( ",8=" + updating );
                values.append( ",9=" + System.getProperty( "os.name" ) );

                String all = values.toString();

                for ( String nameValuePair : all.split( "," ) )
                {
                    String[] parts = nameValuePair.split( "=", 2 );
                    int tag = Integer.parseInt( parts[0].trim() );
                    String value = parts[1];
                    URL celFeedUrl = defaulWorksheet.getCellFeedUrl();
                    //Degub.getInstance().Debug( "->     Registering: Setting at " + ( getNextRow() - 1 ) + " line value " + value );
                    //System.out.println( "->     Registering: Setting at " + ( getNextRow() - 1 ) + " line value " + value );
                    myService.insert( celFeedUrl, new CellEntry( getNextRow() - 1, tag, value ) );
                }

                computeNextRow();
            }
            catch ( IOException ex )
            {
                Degub.getInstance().Debug( ex );
            }
            catch ( AuthenticationException ex )
            {
                Degub.getInstance().Debug( ex );
            }
            catch ( ServiceException ex )
            {
                Degub.getInstance().Debug( ex );
            }
        }
    }

    public boolean needUpdate() throws IOException, ServiceException
    {
        autentic();

        Degub.getInstance().Debug( "Verifing if is necessary update" );

        cellFeedUrl = myWorksheet.getWorksheets().get( 1 ).getCellFeedUrl();
        CellFeed fee = myService.getFeed( cellFeedUrl, CellFeed.class );

        if ( !QuicklyTranslatorFrame.VERSION.equals( ( fee.getEntries().get( 4 ).getCell().getInputValue() ).trim() ) ||
                !w.read( WriteProprierts.VERSION ).equals( ( fee.getEntries().get( 4 ).getCell().getInputValue() ).trim() ) )
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    public void processUpdate() throws IOException, ServiceException
    {
        autentic();

        Degub.getInstance().Debug( "Verifing if is necessary update" );

        cellFeedUrl = myWorksheet.getWorksheets().get( 1 ).getCellFeedUrl();
        CellFeed fee = myService.getFeed( cellFeedUrl, CellFeed.class );

        if ( needUpdate() )
        {

            Degub.getInstance().Debug( "Will update your version..." );
            Updater u = new Updater();
            u.update( ( fee.getEntries().get( 6 ).getCell().getInputValue() ).trim() );
        }
    }

    public static void main( String[] args ) throws MalformedURLException, IOException, IOException, AuthenticationException, ServiceException
    {
        ComputeUsage s = new ComputeUsage();
        s.ComputeUsage();
        s.setData();
    }
}
